package com.gzc.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.gzc.common.Const;
import com.gzc.common.SystemContext;
import com.gzc.model.User;

public class SystemContextFilter implements Filter {

	private int pageSize;
	
	@Override
	public void destroy() {
	
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		try {
			int tps = pageSize;
			try {
				tps = Integer.parseInt(req.getParameter("pageSize"));
			} catch (NumberFormatException e) { }
			
			int pageOffset = 0;
			try {
				pageOffset = Integer.parseInt(req.getParameter("pager.offset"));
			} catch (NumberFormatException e) { }
			
			HttpServletRequest hreq = (HttpServletRequest)req;
			SystemContext.setPageOffset(pageOffset);
			SystemContext.setPageSize(tps);
			
			String realPath = hreq.getSession().getServletContext().getRealPath("");
			realPath = Const.REAL_PATH;
			SystemContext.setRealPath(realPath);
			
			User loginUser = (User)hreq.getSession().getAttribute(Const.LOGIN_USER_KEY);
			if(loginUser != null) SystemContext.setLoginUser(loginUser);
			chain.doFilter(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SystemContext.removePageOffset();
			SystemContext.removePageSize();
			SystemContext.removeLoginUser();
			SystemContext.removeRealPath();
		}
	}

	@Override
	public void init(FilterConfig cfg) throws ServletException {
		pageSize = Integer.parseInt(cfg.getInitParameter("pageSize"));
	}

}
